<template>
  <kr-print-designer ref="printDesigner" @save="handleSave"/>
</template>
<script>
  import {OutStockOptions, InStockOptions} from '../data/options'
  import {edit, view, widget} from '../service/api'

  export default {
    data() {
      return {
        id: '',
        value: {
          title: 'demo',
          width: 750,
          height: 550,
          pageWidth: 750,
          pageHeight: 550,
          tempItems: [],
        },
        widgets: OutStockOptions,
      }
    },

    created() {
      this.id = this.$route.query.id
      try {
        this.view(this.id)
        //this.widgets = this.value.type == 1 ? OutStockOptions : InStockOptions
      } catch (err) {
        console.error(err)
      }
    },
    methods: {
      view(id) {
        view({id: id}).then(res => {
          const data = res.data
          if (data.code == 200) {
            this.value = data.data
            this.widget(data.data.type)
          } else {
            this.$message({
              showClose: true,
              message: data.message || '错误',
              type: 'error'
            });
          }
        }).catch(err => {
          this.$message({
            showClose: true,
            message: data.message || '错误',
            type: 'error'
          });
        })
      },
      widget(type) {
        widget({type: type}).then(res => {
          const data = res.data
          if (data.code == 200) {
            this.widgets = data.data
            this.initTemp()
          } else {
            this.$message({
              showClose: true,
              message: data.message || '错误',
              type: 'error'
            });
          }
        }).catch(err => {
          this.$message({
            showClose: true,
            message: data.message || '错误',
            type: 'error'
          });
        })
      },
      handleSave(data) {
        // this.$router.back()
        console.log('data', data)
        edit(data).then(res => {
          const resData = res.data
          if (resData.code == 200) {
            this.setSuccess(resData)
          } else {
            this.setError(resData)
          }
        }).catch(err => {
          this.setError(resData)
        })
      },
      setSuccess(data) {
        this.$message({
          showClose: true,
          message: data.message || '操作成功',
          type: 'success'
        });
      },
      setError(data) {
        this.$message({
          showClose: true,
          message: data.message || '操作失败',
          type: 'error'
        });
      },
      // 手动初始话模板数据
      initTemp() {
        this.$refs.printDesigner.initTemp(this.value, this.widgets)
      }
    },
  }
</script>
